﻿using JMI_Nucleo.Classe;
using JMI_Nucleo.Enumerador;
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using Devart.Data.PostgreSql;

namespace JMI_Nucleo.JMIProvider
{
    public class BDUtil
    {
        private string nomeProvedor = String.Empty;
        private JMIUtil ObjUtil;
   
        private string servidor;
        private int porta;
        private string bd;
        private string usuario;
        private string senha;
        
        private PgSqlConnection _connPostgresql;
        private MySqlConnection _connMySql;
        private SqlConnection _connSql;

        private string GetStringConexao()
        {
            JMIUtil objUtil = new JMIUtil();
            if (String.IsNullOrEmpty(servidor) && porta == 0 && String.IsNullOrEmpty(usuario))
            {
                var config = objUtil.GetInfoConexao();
                servidor = config.Servidor;
                porta = config.Porta;
                bd = config.Base;
                usuario = config.Usuario;
                senha = config.Senha;
            }

            string strConexao = String.Format("Server={0};Port={1};Database={2};User Id={3};Password={4};",
                     servidor, porta, bd, usuario, senha);
            return strConexao;
        }

        private void ConectaPostgreSQL()
        {
            //_connPostgresql = new PgSqlConnection(GetStringConexao());
            GetStringConexao();
            _connPostgresql = new PgSqlConnection();
            _connPostgresql.Host = servidor;
            _connPostgresql.Port = porta;
            _connPostgresql.Database = bd;
            _connPostgresql.UserId = usuario;
            _connPostgresql.Password = senha;
            _connPostgresql.Unicode = true;
            try
            {
                if (_connPostgresql.State == ConnectionState.Closed)
                {
                    _connPostgresql.Open();
                }
            }
            catch (Exception ex)
            {
                _connPostgresql = null;
                #region Grava log local
                mLog _info = new mLog();
                _info._TipoErro = TipoErro.Erro;
                _info.Mensagem = "Erro na conexão com o banco de dados.; " + ex.Message;
                _info.Metodo = "private void ConectaPostgreSQL()";
                _info.StackTrace = ex.StackTrace;
                _info.Tabela = String.Empty;
                LogLocal.Info = _info;
                LogLocal.Gravar();
                #endregion
            }
        }
        private void ConectaMySQL()
        {
            _connMySql = new MySqlConnection(GetStringConexao());
            try
            {
                if (_connMySql.State == ConnectionState.Closed)
                {
                    _connMySql.Open();
                }
            }
            catch (Exception ex)
            {
                _connMySql = null;
                #region Grava log local
                mLog _info = new mLog();
                _info._TipoErro = TipoErro.Erro;
                _info.Mensagem = "Erro na conexão com o banco de dados.; " + ex.Message;
                _info.Metodo = "private void ConectaMySQL()";
                _info.StackTrace = ex.StackTrace;
                _info.Tabela = String.Empty;
                LogLocal.Info = _info;
                LogLocal.Gravar();
                #endregion
            }
        }
        private void ConectaSQLServer()
        {
            _connSql = new SqlConnection(GetStringConexao());
            try
            {
                if (_connSql.State == ConnectionState.Closed)
                {
                    _connSql.Open();
                }
            }
            catch (Exception ex)
            {
                _connSql = null;
                #region Grava log local
                mLog _info = new mLog();
                _info._TipoErro = TipoErro.Erro;
                _info.Mensagem = "Erro na conexão com o banco de dados.; " + ex.Message;
                _info.Metodo = "private void ConectaSQLServer()";
                _info.StackTrace = ex.StackTrace;
                _info.Tabela = String.Empty;
                LogLocal.Info = _info;
                LogLocal.Gravar();
                #endregion
            }
        }

        public DbConnection ConexaoAtiva()
        {
            DbConnection conexaoLocal = null;

            ObjUtil = new JMIUtil();
            nomeProvedor = ObjUtil.GetProvedorUtilizado();

            if (nomeProvedor == "Npgsql")
            {
                ConectaPostgreSQL();
                conexaoLocal = _connPostgresql;
            }
            else if (nomeProvedor == "System.Data.SqlClient")
            {
                ConectaMySQL();
                conexaoLocal = _connSql;
            }
            else if (nomeProvedor == "MySql.Data.MySqlClient")
            {
                ConectaSQLServer();
                conexaoLocal = _connMySql;
            }
            return conexaoLocal;
        }
    }
}
